#include "hloop.h"
#include "hthread.h"
#include <iostream>

void longRunningTask(hloop_t* loop, int x, int y) {
    std::this_thread::sleep_for(std::chrono::seconds(2));
    int result = x + y;
    
    // 发送自定义事件到事件循环
    hevent_t ev;
    memset(&ev, 0, sizeof(ev));
    ev.event_type = HEVENT_TYPE_CUSTOM;
    ev.cb = [](hevent_t* ev) {
        int* result = (int*)hevent_userdata(ev);
        std::cout << "Task result: " << *result << std::endl;
        delete result;
    };
    ev.userdata = new int(result);
    hloop_post_event(loop, &ev);
}

HTHREAD_ROUTINE(longRunningThread) {
        hloop_t* loop = (hloop_t*)userdata;
        longRunningTask(loop, 10, 20);
        return (void*)0;
    }
int main() {
    hloop_t* loop = hloop_new(0);

    // 创建新线程执行任务
    hthread_t thread =  hthread_create(longRunningThread, loop);

    // 运行事件循环
    hloop_run(loop);

    // 清理资源
    hthread_join(thread);
    hloop_free(&loop);

    return 0;
}